package com.example.snackfood.controller;

import com.alibaba.fastjson2.JSON;
import com.example.snackfood.entity.Comments;
import com.example.snackfood.entity.Users;
import com.example.snackfood.services.IsnackFoodCommentService;
import com.example.snackfood.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @program: snackFood
 * @description:
 * @author: lydms
 * @create: 2023-11-23 13:14
 **/

@RestController
@RequestMapping("/Comments")
public class SnackFoodCommentController {


    @Autowired
    private IsnackFoodCommentService snackFoodCommentService;


    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 成功加入评论
     * @param comments
     * @return
     */
    @PostMapping("/add")
    public R addComment(@RequestBody Comments comments){
        snackFoodCommentService.add(comments);
        return R.success("成功加入评论");
    }

    /**
     * reids增加
     * @param id
     * @return
     */
    @GetMapping("/putObj")
    public R putObj(@RequestParam Long id) {
        Comments comments = snackFoodCommentService.selectCommentById(id);
        String json = JSON.toJSONString(comments);
        System.out.println(json);
        redisTemplate.opsForValue().set(id.toString(), json, 1, TimeUnit.HOURS);
        return R.success(comments);
    }


    @GetMapping("/getObj")
    public R getObj(@RequestParam Long id) {
        String json = (String) redisTemplate.opsForValue().get(id.toString());
        System.out.println(json);
        Comments comments = new Comments();
        if (json == null) {
            System.out.println("redis 没有该信息");

            comments = snackFoodCommentService.selectCommentById(id);
            String shopStr = JSON.toJSONString(comments);
            System.out.println(shopStr);
            // 放到redis
            redisTemplate.opsForValue().set(id.toString(), shopStr, 1, TimeUnit.HOURS);
        } else {
            System.out.println("redis 中存在该信息：" + json);
            comments = JSON.parseObject(json, Comments.class);
        }
        return R.success(comments);
    }

    /**
     * 删除评论
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public R deleteComment(@PathVariable Long id){
        snackFoodCommentService.deleteComment(id);
        return R.success("成功删除该评论");
    }
}
